package com.dkm.orproject.dkmoa.action.flow;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaEntryAlterationFlow;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.domain.OaRegularFlow;
import com.dkm.orproject.dkmoa.service.flow.OaEntryAlterationFlowService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.Tools;
import io.swagger.annotations.*;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName : OaEntryAlterationFlowAction  //类名
 * @Description : 人员信息变更流程  //描述
 * @Author : 易嵘  //作者
 * @Date: 2020-11-18 10:06  //时间
 */
@RestController
@RequestMapping("OaEntryAlterationFlowAction")
@Api(tags = "人员信息变更流程")
public class OaEntryAlterationFlowAction {

    /**
     * 人员信息变更流程服务接口
     */
    @Resource
    OaEntryAlterationFlowService entryAlterationFlowService;

    @Resource
    Tools tools;


    /**
     * 回调值
     */
    int row=0;

    /**
     * 日志
     */
    OaLog log;

    /**
     * 登陆人
     */
    OaPersonnel personnel;

    /**
     * 回调map
     */
    Map<String,Object> map;

    /**
     * 分页查询
     * @param entryAlterationName 人员信息变更流程模型 用于条件查询
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param page 当前页数
     * @param limit 显示的行数
     * @return 人员信息变更流程集
     */
    @ApiOperation(value = "人员信息变更分页查询接口", notes = "人员信息变更流程分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "entryAlterationName",value = "人员信息变更流程名称（模糊）",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "显示行数", required = true, dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaRegularFlow.class),
    })
    @UserLoginToken
    @GetMapping("findAll")
    public Map<String,Object> findAll(String entryAlterationName,
                                      String startTime,
                                      String endTime,
                                      Integer page,
                                      Integer limit,
                                      HttpServletRequest request){
        try{
            List<OaEntryAlterationFlow> dataDictionaries=entryAlterationFlowService.findAll(entryAlterationName,startTime,endTime,page,limit);
            Long rowCount=entryAlterationFlowService.rowCount(entryAlterationName,startTime,endTime);
            return Tools.maps(dataDictionaries,rowCount);
        }catch (Exception e){
            addErrorLog(request,"人员信息变更流程分页查询",e);
        }
        return null;

    }

    /**
     * id查询
     * @param id 人员信息变更流程主键
     * @return 人员信息变更流程模型
     */
    @ApiOperation(value = "id查询", notes = "id查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "人员信息变更流程id",dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaRegularFlow.class),
    })
    @UserLoginToken
    @GetMapping("findById/{id}")
    public OaEntryAlterationFlow findById(@PathVariable("id") Long id, HttpServletRequest request){
        try{
            return entryAlterationFlowService.findById(id);
        }catch (Exception e){
            addErrorLog(request,"人员信息变更流程id查询",e);
        }
        return null;
    }

    /**
     * 查询报错日志新增
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title 模块标题
     * @param e 异常参数
     */
    private void addErrorLog(HttpServletRequest request,String title,Exception e){
        e.printStackTrace();
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        log=new OaLog();
        log.setLogType("0");
        log.setLogBody(e.getLocalizedMessage());
        log.setLogTitle(title);
        log.setLogIp(request.getRemoteAddr());
        if(ObjectUtils.isEmpty(personnel)){
            log.setCreatedBy(personnel.getPersonnelName());
        }
        tools.errorMap(log);
    }

    /**
     * 起草人节点
     * @param request 服务器请求
     * @return 回调函数
     */
    @ApiOperation(value = "起草人节点", notes = "起草人节点")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "affirmTime",value = "入职时间",dataType = "Date",paramType = "query"),
            @ApiImplicitParam(name = "personnelId",value = "申请人id",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "提交成功"),
    })
    @UserLoginToken
    @PostMapping("add")
    public Map<String,Object> add(Long entryId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            response.sendRedirect("pages/dkmoa/login.html");
            return tools.rowMap(map,0,null);
        }
        try{
            OaEntryAlterationFlow entryAlterationFlow=new OaEntryAlterationFlow();
            entryAlterationFlow.setEntryId(entryId);
            row=entryAlterationFlowService.add(entryAlterationFlow,personnel);
            log.setLogTitle("人员信息变更流程新增");
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(entryAlterationFlow).toString());
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"人员信息变更流程新增",e);
        }
        return map;
    }

    /**
     * 人事审核通过
     * @param request 服务器请求
     * @param entryAlterationFlow 人事审核信息
     * @return 回调函数
     */
    @ApiOperation(value = "人事审核通过", notes = "人事审核通过")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pkRegularId",value = "人员信息变更流程id",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name = "regularPersonnelOpinion",value = "人员信息变更流程id",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "提交成功"),
    })
    @UserLoginToken
    @PostMapping("staffingPass")
    public Map<String,Object> staffingPass(HttpServletRequest request,OaEntryAlterationFlow entryAlterationFlow){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            row=entryAlterationFlowService.staffingPass(entryAlterationFlow,personnel);
            log.setLogTitle("人事审核通过");
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(entryAlterationFlow).toString());
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"人事审核通过",e);
        }
        return map;
    }

    /**
     * 人事审核不通过
     * @param request 服务器请求
     * @param entryAlterationFlow 人事审核信息
     * @param formReason 不通过原因
     * @return 回调函数
     */
    @ApiOperation(value = "人事审核不通过", notes = "人事审核不通过")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pkRegularId",value = "人员信息变更流程id",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name = "formReason",value = "不同意意见",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "提交成功"),
    })
    @UserLoginToken
    @PostMapping("staffingNoPass")
    public Map<String,Object> staffingNoPass(HttpServletRequest request,OaEntryAlterationFlow entryAlterationFlow,String formReason){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            row=entryAlterationFlowService.staffingNoPass(entryAlterationFlow,personnel,formReason);
            log.setLogTitle("人事审核不通过");
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(entryAlterationFlow).toString());
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"人事审核不通过",e);
        }
        return map;
    }

    /**
     * 批量删除
     * @param ids 人员信息变更流程id集
     * @param request 服务器请求
     * @return 回调函数
     */
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids",value = "人员信息变更流程批量id",dataType = "Long[]",paramType = "query"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "提交成功"),
    })
    @UserLoginToken
    @DeleteMapping("deleteAll")
    public Map<String,Object> deleteAll(@RequestParam(value = "ids[]",required = false) Long[] ids,HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            List<Long> list= Arrays.asList(ids);
            List<OaEntryAlterationFlow> dataDictionaries=entryAlterationFlowService.selectAll(list);
            row=entryAlterationFlowService.deleteAll(list);
            log.setLogTitle("人员信息变更流程批量删除");
            log.setLogBody(JSON.toJSON(dataDictionaries).toString());
            log.setLogType("1");
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"人员信息变更流程批量删除",e);
        }
        return map;
    }

    /**
     * id删除
     * @param id 人员信息变更流程id
     * @param request 服务器请求
     * @return 回调函数
     */
    @ApiOperation(value = "id删除", notes = "id删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "人员信息变更流程id",dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "删除成功"),
    })
    @UserLoginToken
    @DeleteMapping("deleteById/{id}")
    public Map<String,Object> deleteById(@PathVariable(value = "id",required = false)Long id,HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            OaEntryAlterationFlow flow=entryAlterationFlowService.findById(id);
            row=entryAlterationFlowService.deleteById(id);
            log.setLogTitle("人员信息变更流程删除");
            log.setLogBody(JSON.toJSON(flow).toString());
            log.setLogType("1");
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"人员信息变更流程删除",e);
        }
        return map;
    }

    /**
     * 优化代码
     * @param request 服务器请求
     */
    private void rowMap(HttpServletRequest request){
        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if(ObjectUtils.isEmpty(personnel)){
            return;
        }
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }

    /**
     * 日期格式化
     *
     * @param binder 服务器参数转换器
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}
